package com.ys.fmms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ys.fmms.mapper.RoleMapper;
import com.ys.fmms.pojo.Role;
import com.ys.fmms.pojo.UserRole;
import com.ys.fmms.service.RoleService;
import com.ys.fmms.service.UserRoleService;
import com.ys.fmms.util.TimeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "roleServiceImpl")
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private UserRoleService userRoleService;

    /**
     * 这个接口需要对传递回来的userId
     * 先进行根据id删除 然后在分配角色
     * @param userId
     * @param roleIds
     */
    @Override
    public void assignRoleByUserId(String userId, List<String> roleIds) {
        // 根据id删除已分配的角色
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        userRoleService.remove(wrapper);
        // 分配角色
        List<UserRole> userRoleList =roleIds.stream().map(item->{
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(item);
            userRole.setCreateTime(TimeUtils.currentDate());
            userRole.setModifyTime(TimeUtils.currentDate());
            return userRole;
        }).collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
    }

    @Override
    public IPage<Role> getRoleListByPageAndRoleName(Page<Role> rolePage, String roleName) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if(StringUtils.hasText(roleName)){
            wrapper.like("role_name",roleName);
        }
        wrapper.orderByAsc("id");
        IPage<Role> roleIPage = baseMapper.selectPage(rolePage,wrapper);
        return roleIPage;
    }
}
